/*
 * #%L
 * SwiftUIWeb Maven Webapp
 * $Id:$
 * $HeadURL:$
 * %%
 * Copyright (C) 2011 - 2012 Linkwithweb
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
package com.linkwithweb.products.swiftui.controller;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.linkwithweb.products.swiftui.context.DBUpdateStatement;
import com.linkwithweb.products.swiftui.context.SystemContext;
import com.linkwithweb.products.swiftui.dao.impl.DBHelper;
import com.linkwithweb.products.swiftui.dataobject.FrameworkTransaction;
import com.linkwithweb.products.swiftui.service.PlatformService;
import com.linkwithweb.products.swiftui.utils.ObjectSerializer;

/**
 * @author ashwin kumar
 * 
 */
@Controller
public class JQGridController extends AbstractController {

	@Autowired
	@Qualifier("platformService")
	private PlatformService platformService;
	static String DB_TYPE = "MYSQL";

	/**
	 * Constructor
	 */
	public JQGridController() {
	}

	@RequestMapping("/jqGridConfig")
	public ModelAndView jqGridConfig(@RequestParam(value = "gridName") String gridName) {
		Map<String, Object> paramMap = new HashMap<String, Object>();

		StringBuffer querySQL = new StringBuffer();
		if (StringUtils.equalsIgnoreCase(gridName, "DSB_CLASSES")) {
			querySQL.append("SELECT * FROM DBO.DSB_CLASSES");
		} else if (StringUtils.equalsIgnoreCase(gridName, "DSB_TEACHERS")) {
			querySQL.append("SELECT * FROM DBO.DSB_TEACHERS");
		} else if (StringUtils.equalsIgnoreCase(gridName, "DSB_STUDENTS")) {
			querySQL.append("SELECT * FROM DBO.DSB_STUDENTS");
		} else if (StringUtils.equalsIgnoreCase(gridName, "USR_LOOKUP")) {
			querySQL
					.append("SELECT * FROM (SELECT std.StudentNumber,std.Username,tch.TeacherEmailAddress,SCH.SchoolName,PRM.ProgramType FROM dbo.dsb_Programs PRM,dbo.dsb_Schools SCH,dbo.dsb_Teachers TCH,dbo.dsb_Students STD where tch.TeacherID = STD.TeacherID AND SCH.SchoolID = TCH.SchoolID AND TCH.ProgramID = PRM.ProgramID AND SCH.SchoolID = STD.SchoolID) X");
		} else if (StringUtils.equalsIgnoreCase(gridName, "MDR_LOOKUP")) {
			querySQL
					.append("SELECT * FROM (SELECT SCH.MDRPID,SCH.SchoolName,dis.DistrictName,dis.Zipcode FROM dbo.dsb_Schools SCH,dbo.dsb_Districts dis where dis.DistrictID = SCH.DistrictID) X");
		} else if (StringUtils.equalsIgnoreCase(gridName, "DELETED_CLASSES")) {
			querySQL
					.append("SELECT * FROM (select cleaned.class_name,cleaned.class_number,cleaned.grade,schools.SchoolName,districts.DistrictName,ProgramName = (case cleaned.ProgramId when 7 then 'Science' else 'reach' end )  from classes_cleaned cleaned join dsb_Schools schools on cleaned.schoolid = schools.SchoolID  join dsb_Districts districts on schools.DistrictID = districts.DistrictID ) X");
		} else if (StringUtils.equalsIgnoreCase(gridName, "FRM_WORKFLOW_TRANSACTION")) {
			String roleId = SystemContext.getInstance().getUserContext().getRole();
			querySQL
					.append(
							"SELECT * FROM (SELECT FWT.UNIQUE_KEY,FWT.TRANSACTION_ID,FWT.ACTED_BY,FWT.APPROVAL_STATUS,FWT.TABLE_NAME FROM FRM_WORKFLOW_TRANSACTION FWT JOIN FRM_USERS FU ON FWT.CREATED_BY=FU.UNIQUE_KEY")
					.append(" where FWT.IS_ACTIVE = '1' AND FWT.ROLE_ID = '").append(roleId).append("') x");
		} else {
			querySQL.append("SELECT * FROM ").append(gridName);
		}

		Map<String, String> metaData = DBHelper.getInstance().getMetaDataForSQL(querySQL.toString(), true);
		List<String> columnNames = new ArrayList<String>();

		for (String colName : metaData.keySet()) {
			if (isSystemColumn(colName)) {
				continue;
			}
			columnNames.add(colName);
		}

		// String[] columnNames = metaData.keySet().toArray(new String[0]);

		String primaryKey = columnNames.get(0);

		try {
			List<String> primaryKeys = DBHelper.getInstance().getPrimaryKeys(gridName, true);
			primaryKey = primaryKeys.get(0);
		} catch (Exception e) {
			// TODO: handle exception
		}

		paramMap.put("colDisplayNames", columnNames.toArray());
		paramMap.put("colNames", columnNames.toArray());
		paramMap.put("gridName", gridName);
		paramMap.put("primaryKey", primaryKey);
		paramMap.put("metaData", metaData);

		return new ModelAndView("jqgrid/JQGridDefinition", paramMap);
	}

	/**
	 * @param httpServletRequest
	 * @param httpServletResponse
	 * @return
	 */
	@RequestMapping("/jqGridEdit")
	public ModelAndView jqGridEdit(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
		String gridName = httpServletRequest.getParameter("gridName");
		String operation = httpServletRequest.getParameter("oper");

		Map<String, Object> paramMap = new HashMap<String, Object>();

		if (StringUtils.equalsIgnoreCase(gridName, "frm_workflow_transaction")) {
			handleWorkflowProcessing(httpServletRequest, httpServletResponse);
			return new ModelAndView("blank", paramMap);
		}

		StringBuffer querySQL = new StringBuffer();
		if (StringUtils.equalsIgnoreCase(gridName, "DSB_CLASSES")) {
			querySQL.append("SELECT * FROM DBO.DSB_CLASSES");
		} else if (StringUtils.equalsIgnoreCase(gridName, "DSB_TEACHERS")) {
			querySQL.append("SELECT * FROM DBO.DSB_TEACHERS");
		} else if (StringUtils.equalsIgnoreCase(gridName, "DSB_STUDENTS")) {
			querySQL.append("SELECT * FROM DBO.DSB_STUDENTS");
		} else if (StringUtils.equalsIgnoreCase(gridName, "USR_LOOKUP")) {
			querySQL
					.append("SELECT * FROM (SELECT std.StudentNumber,std.Username,tch.TeacherEmailAddress,SCH.SchoolName,PRM.ProgramType  FROM dsb_Programs PRM  JOIN dsb_Teachers TCH ON TCH.ProgramID = PRM.ProgramID JOIN dsb_Schools SCH ON TCH.SchoolID = SCH.SchoolID RIGHT OUTER JOIN dsb_Students STD ON (SCH.SchoolID = STD.SchoolID AND TCH.TeacherID = STD.TeacherID )) X");
		} else if (StringUtils.equalsIgnoreCase(gridName, "MDR_LOOKUP")) {
			querySQL
					.append("SELECT * FROM (SELECT SCH.MDRPID,SCH.SchoolName,dis.DistrictName,dis.Zipcode FROM dbo.dsb_Schools SCH,dbo.dsb_Districts dis where dis.DistrictID = SCH.DistrictID) X");
		} else if (StringUtils.equalsIgnoreCase(gridName, "FRM_WORKFLOW_TRANSACTION")) {
			String roleId = SystemContext.getInstance().getUserContext().getRole();
			querySQL
					.append(
							"SELECT * FROM (SELECT FWT.UNIQUE_KEY,FWT.TRANSACTION_ID,FWT.ACTED_BY,FWT.APPROVAL_STATUS,FWT.TABLE_NAME FROM FRM_WORKFLOW_TRANSACTION FWT JOIN FRM_USERS FU ON FWT.CREATED_BY=FU.UNIQUE_KEY")
					.append(" where FWT.IS_ACTIVE = '1' AND FWT.ROLE_ID = '").append(roleId).append("') x");
		} else {
			querySQL.append("SELECT * FROM ").append(gridName);
		}

		Map<String, String> metaData = DBHelper.getInstance().getMetaDataForSQL(querySQL.toString(), true);
		// String[] columnNames = metaData.keySet().toArray(new String[0]);
		List<String> columnNames = new ArrayList<String>();

		for (String colName : metaData.keySet()) {
			if (isSystemColumn(colName)) {
				continue;
			}
			columnNames.add(colName);
		}

		paramMap.put("colDisplayNames", columnNames.toArray());
		paramMap.put("colNames", columnNames.toArray());
		paramMap.put("gridName", gridName);
		paramMap.put("metaData", metaData);
		/**
		 * Build Operation SQL
		 */
		querySQL = new StringBuffer();
		StringBuffer queryArgsSQL = new StringBuffer();
		List arguments = new ArrayList();
		if (StringUtils.equalsIgnoreCase(operation, "ADD")) {
			List<String> primaryKeys = DBHelper.getInstance().getPrimaryKeys(gridName, true);
			String primaryKey = primaryKeys.get(0);

			querySQL.append("INSERT INTO ").append(gridName).append(" (");

			for (String columnName : columnNames) {
				if (!StringUtils.equalsIgnoreCase(primaryKey, columnName)) {
					String paramValue = httpServletRequest.getParameter(columnName);
					if (StringUtils.isNotBlank(paramValue)) {
						arguments.add(paramValue);
					} else {
						arguments.add(null);
					}
				} else {
					continue;
				}
				if (arguments.size() > 1) {
					querySQL.append(",").append(columnName);
					queryArgsSQL.append(",?");
				} else {
					querySQL.append(columnName);
					queryArgsSQL.append("?");
				}
			}
			/**
			 * End Bracket
			 */
			querySQL.append(") VALUES (").append(queryArgsSQL.toString()).append(")");

			DBHelper.getInstance().getJdbcTemplate("jdbcTemplate").update(querySQL.toString(), arguments.toArray());

		} else if (StringUtils.equalsIgnoreCase(operation, "edit")) {
			List<String> primaryKeys = DBHelper.getInstance().getPrimaryKeys(gridName, true);
			String primaryKey = primaryKeys.get(0);

			querySQL.append("UPDATE ").append(gridName).append(" SET ");

			for (String columnName : columnNames) {
				if (!StringUtils.equalsIgnoreCase(primaryKey, columnName)) {
					String paramValue = httpServletRequest.getParameter(columnName);
					if (StringUtils.isNotBlank(paramValue)) {
						arguments.add(paramValue);
					} else {
						arguments.add(null);
					}
				} else {
					continue;
				}
				if (arguments.size() > 1) {
					querySQL.append(",").append(columnName).append("= ?");
				} else {
					querySQL.append(columnName).append(" = ?");
				}
			}
			/**
			 * End Bracket
			 */
			querySQL.append(" WHERE ").append(primaryKey).append(" = ").append(httpServletRequest.getParameter("id"));

			DBHelper.getInstance().getJdbcTemplate("jdbcTemplate").update(querySQL.toString(), arguments.toArray());

		} else {
			List<String> primaryKeys = DBHelper.getInstance().getPrimaryKeys(gridName, true);
			String primaryKey = primaryKeys.get(0);
			DBHelper.getInstance().getJdbcTemplate("jdbcTemplate").execute(
					"DELETE FROM " + gridName + " where " + primaryKey + " = "
							+ httpServletRequest.getParameter("id").replaceAll(",", ""));
		}

		return new ModelAndView("blank", paramMap);
	}

	/**
	 * @param httpServletRequest
	 * @param httpServletResponse
	 */
	@RequestMapping("/handleWorkflowProcessing")
	private @ResponseBody String handleWorkflowProcessing(HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse) {
		String transactionIdString = httpServletRequest.getParameter("TRANSACTION_ID");
		String approvalMode = httpServletRequest.getParameter("approvalMode");

		if (transactionIdString == null || approvalMode == null) {
			return "Error: No TransactionID";
		}

		String[] transactionIds = transactionIdString.split(",");

		for (String transactionId : transactionIds) {
			if(StringUtils.equalsIgnoreCase(transactionId, "-1")){
				continue;
			}
			FrameworkTransaction transaction = new FrameworkTransaction();
			transaction.setTransactionId(transactionId);

			getPlatformService().changeTransactionStatus(transaction, approvalMode);
		}

		return "Success";
	}

	/**
	 * @param httpServletRequest
	 * @param httpServletResponse
	 * @return
	 */
	@RequestMapping("/jqGridData")
	public ModelAndView jqGridData(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
		Map<String, Object> paramMap = new HashMap<String, Object>();

		String gridName = httpServletRequest.getParameter("gridName");
		String page = httpServletRequest.getParameter("page");
		String rows = httpServletRequest.getParameter("rows");
		String sidx = httpServletRequest.getParameter("sidx");
		String sord = httpServletRequest.getParameter("sord");

		int offset = (Integer.parseInt(page) - 1) * Integer.parseInt(rows);
		int rowCount = Integer.parseInt(rows);
		int endRow = offset + rowCount;

		StringBuffer querySQL = new StringBuffer();
		if (StringUtils.equalsIgnoreCase(gridName, "DSB_CLASSES")) {
			querySQL.append("SELECT * FROM DBO.DSB_CLASSES");
			if (StringUtils.equalsIgnoreCase(sidx, "id")) {
				sidx = "ClassId";
			}

		} else if (StringUtils.equalsIgnoreCase(gridName, "DSB_TEACHERS")) {
			querySQL.append("SELECT * FROM DBO.DSB_TEACHERS");
			if (StringUtils.equalsIgnoreCase(sidx, "id")) {
				sidx = "TeacherId";
			}
		} else if (StringUtils.equalsIgnoreCase(gridName, "DSB_STUDENTS")) {
			querySQL.append("SELECT * FROM DBO.DSB_STUDENTS");
			if (StringUtils.equalsIgnoreCase(sidx, "id")) {
				sidx = "StudentId";
			}
		} else if (StringUtils.equalsIgnoreCase(gridName, "USR_LOOKUP")) {
			querySQL
					.append("SELECT * FROM (SELECT std.StudentNumber,std.Username,tch.TeacherEmailAddress,SCH.SchoolName,PRM.ProgramType FROM dbo.dsb_Programs PRM,dbo.dsb_Schools SCH,dbo.dsb_Teachers TCH,dbo.dsb_Students STD where tch.TeacherID = STD.TeacherID AND SCH.SchoolID = TCH.SchoolID AND TCH.ProgramID = PRM.ProgramID AND SCH.SchoolID = STD.SchoolID) X");
			if (StringUtils.equalsIgnoreCase(sidx, "id")) {
				sidx = "Username";
			}
		} else if (StringUtils.equalsIgnoreCase(gridName, "MDR_LOOKUP")) {
			querySQL
					.append("SELECT * FROM (SELECT SCH.MDRPID,SCH.SchoolName,dis.DistrictName,dis.Zipcode FROM dbo.dsb_Schools SCH,dbo.dsb_Districts dis where dis.DistrictID = SCH.DistrictID) X");
			if (StringUtils.equalsIgnoreCase(sidx, "id")) {
				sidx = "MDRPID";
			}
		} else if (StringUtils.equalsIgnoreCase(gridName, "DELETED_CLASSES")) {
			querySQL
					.append("SELECT * FROM (select cleaned.class_name as className,cleaned.class_number,cleaned.grade,schools.SchoolName,districts.DistrictName,ProgramName = (case cleaned.ProgramId when 7 then 'Science' else 'reach' end )  from classes_cleaned cleaned join dsb_Schools schools on cleaned.schoolid = schools.SchoolID  join dsb_Districts districts on schools.DistrictID = districts.DistrictID) X");
			if (StringUtils.equalsIgnoreCase(sidx, "id")) {
				sidx = "className";
			}
		} else if (StringUtils.equalsIgnoreCase(gridName, "FRM_WORKFLOW_TRANSACTION")) {
			String roleId = SystemContext.getInstance().getUserContext().getRole();
			querySQL
					.append(
							"SELECT * FROM (SELECT FWT.UNIQUE_KEY,FWT.TRANSACTION_ID,FWT.ACTED_BY,FWT.APPROVAL_STATUS,FWT.TABLE_NAME FROM FRM_WORKFLOW_TRANSACTION FWT JOIN FRM_USERS FU ON FWT.CREATED_BY=FU.UNIQUE_KEY")
					.append(" where FWT.IS_ACTIVE = '1' AND FWT.ROLE_ID = '").append(roleId).append("') x");
			sidx = "UNIQUE_KEY";
		} else {
			querySQL.append("SELECT * FROM ").append(gridName);
			sidx = "UNIQUE_KEY";
		}

		Map<String, String> metaData = DBHelper.getInstance().getMetaDataForSQL(querySQL.toString(), true);

		List<String> columnNames = new ArrayList<String>();

		for (String colName : metaData.keySet()) {
			if (isSystemColumn(colName)) {
				continue;
			}
			columnNames.add(colName);
		}
		paramMap.put("colDisplayNames", columnNames.toArray());
		paramMap.put("colNames", columnNames.toArray());
		paramMap.put("metaData", metaData);

		/**
		 * Add dummy condition so that all subsequent conditions are and
		 */
		int whereIndex = StringUtils.lastIndexOf(querySQL.toString().toUpperCase(), "WHERE");
		int endBracketIndex = StringUtils.lastIndexOf(querySQL.toString().toUpperCase(), ")");

		if (whereIndex < endBracketIndex) {
			querySQL = querySQL.append(" WHERE 1=1");
		} else {
			if (StringUtils.containsIgnoreCase(querySQL.toString().toUpperCase(), "where")) {
			} else {
				querySQL = querySQL.append(" WHERE 1=1");
			}
		}

		/**
		 * NOW Build Query for Data. And add conditions
		 */
		for (String columnName : columnNames) {
			String requestValue = httpServletRequest.getParameter(columnName);
			if (StringUtils.isNotBlank(requestValue)) {

				if (StringUtils.containsIgnoreCase(columnName, "id")
						|| StringUtils.containsIgnoreCase(columnName, "key")
						|| StringUtils.containsIgnoreCase(columnName, "date")) {
					if (StringUtils.equalsIgnoreCase(columnName, "TRANSACTION_ID")) {
						querySQL.append(" AND ").append(columnName).append(" LIKE '%").append(requestValue)
								.append("%'");
					} else {
						querySQL.append(" AND ").append(columnName).append(" = '").append(requestValue).append("'");
					}
				} else {
					querySQL.append(" AND ").append(columnName).append(" LIKE '%").append(requestValue).append("%'");
				}
			}
		}

		/**
		 * Now get total Number of Rows to display
		 */
		int recordCount = DBHelper.getInstance().getJdbcTemplate("jdbcTemplate").queryForInt(
				"SELECT COUNT(*) FROM (" + querySQL + ") ABC");
		paramMap.put("recordCount", recordCount);
		paramMap.put("pageCount", (recordCount / rowCount) + 1);
		String finalSQL = "";
		/**
		 * Now build sort/limit condition
		 */
		if (StringUtils.equalsIgnoreCase(DB_TYPE, "SQLSERVER")) {
			String intermittentSQL = querySQL.toString();
			intermittentSQL = intermittentSQL.replaceFirst("SELECT", "SELECT ROW_NUMBER() OVER ( ORDER BY " + sidx
					+ " " + sord + " ) AS RowNum,");

			finalSQL = "SELECT * FROM (" + intermittentSQL + " ) AS RowConstrainedResult WHERE RowNum >= " + offset
					+ " AND RowNum < " + endRow + " ORDER BY RowNum";
		}else if (StringUtils.equalsIgnoreCase(DB_TYPE, "ORACLE")) {
			String intermittentSQL = querySQL.toString();
			// SELECT * FROM ( SELECT a.*, ROWNUM rnum FROM ( query ) a WHERE
			// ROWNUM < 20 ) WHERE rnum >= 10;
			finalSQL = "SELECT * FROM  ( SELECT  a.*, ROWNUM as rnum FROM ( "
					+ intermittentSQL + " ) a  WHERE ROWNUM < " + endRow
					+ " ) WHERE rnum >= " + offset;
		} else if (StringUtils.equalsIgnoreCase(DB_TYPE, "MYSQL")) {
			if (StringUtils.isNotBlank(sord)) {
				querySQL.append(" ORDER BY ").append(sidx).append(" ").append(sord);
			}
			querySQL.append(" LIMIT ").append(offset).append(",").append(endRow);
			finalSQL = querySQL.toString();
		}

		List<Map<String, Object>> rowData = DBHelper.getInstance().getJdbcTemplate("jdbcTemplate").queryForList(
				finalSQL);
		paramMap.put("rowData", rowData);
		paramMap.put("pageNumber", page);
		/**
		 * Now lets build query which can handle limits
		 */

		return new ModelAndView("jqgrid/JQGridData", paramMap);
	}

	@RequestMapping("/loadTransactionPayload")
	public @ResponseBody
	String loadTransactionPayload(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
		String transactionId = httpServletRequest.getParameter("TRANSACTION_ID");
		FrameworkTransaction transaction = getPlatformService().loadWorkflowTransaction(transactionId);

		DBUpdateStatement dbUpdateStatement = (DBUpdateStatement) ObjectSerializer.convertStringToObject(transaction
				.getTransactionPayload());

		String statementType = "INSERT";
		if (StringUtils.containsIgnoreCase(dbUpdateStatement.getUpdateStatement(), "update")) {
			statementType = "UPDATE";
		} else if (StringUtils.containsIgnoreCase(dbUpdateStatement.getUpdateStatement(), "DELETE")) {
			statementType = "DELETE";
		} else if (StringUtils.containsIgnoreCase(dbUpdateStatement.getUpdateStatement(), "create ")) {
			statementType = "CREATE";
		}

		StringBuffer payloadBuffer = new StringBuffer();
		payloadBuffer.append("<div><h2>").append(dbUpdateStatement.getTableName()).append("(").append(statementType)
				.append(")</h2>");
		payloadBuffer.append("<table>");

		for (int index = 0; index < dbUpdateStatement.getArguments().size(); index++) {
			payloadBuffer.append("<tr><td>").append(dbUpdateStatement.getColumnNames().get(index))
					.append("::</td><td>").append(dbUpdateStatement.getArguments().get(index)).append("</td></tr>");
		}
		payloadBuffer.append("</table></div>");

		// return
		// StringEscapeUtils.escapeHtml(prettyFormat(transaction.getTransactionPayload(),2));
		return payloadBuffer.toString();
	}

	public static String prettyFormat(String input, int indent) {
		try {
			Source xmlInput = new StreamSource(new StringReader(input));
			StringWriter stringWriter = new StringWriter();
			StreamResult xmlOutput = new StreamResult(stringWriter);
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			transformerFactory.setAttribute("indent-number", indent);
			Transformer transformer = transformerFactory.newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.transform(xmlInput, xmlOutput);
			return xmlOutput.getWriter().toString();
		} catch (Exception e) {
			throw new RuntimeException(e); // simple exception handling, please
											// review it
		}
	}

}
